1"use client";
2
3import { useEffect } from "react";
4import { useParams, useRouter } from "next/navigation";
5import { useQuery } from "@tanstack/react-query";
6import { workspaceApi } from "@/lib/api";
7import { sortByPosition } from "@/lib/utils";
8
9
17export default function WorkspaceIndexPage() {
18 const params = useParams<{ workspace: string }>();
19 const slugOrId = params?.workspace ?? "default";
20 const router = useRouter();
21 const isDefault = slugOrId === "default";
22
23
24
25 const workspaces = useQuery({
26 queryKey: ["workspaces"],
27 queryFn: () => workspaceApi.list(),
28 enabled: isDefault,
29 retry: false
30 });
31 useEffect(() => {
32 const first = workspaces.data?.[0];
33 if (isDefault && first) {
34 router.replace(`/w/${first.id}`, { scroll: false });
35 }
36 }, [isDefault, workspaces.data, router]);
37
38 const workspace = useQuery({
39 queryKey: ["workspaces", slugOrId],
40 queryFn: () => workspaceApi.get(slugOrId),
41
42 enabled: slugOrId.length > 0 && !isDefault,
43 retry: false
44 });
45
46 const pages = useQuery({
47 queryKey: ["workspaces", slugOrId, "pages", "index"],
48 queryFn: () => workspaceApi.pages(slugOrId, { parent: null, limit: 100 }),
49 enabled: Boolean(workspace.data?.id),
50 retry: false
51 });
52
53 useEffect(() => {
54 if (!workspace.data?.id) return;
55 const wsId = workspace.data.id;
56 const list = pages.data ? sortByPosition(pages.data) : [];
57 if (list.length > 0) {
58 router.replace(`/w/${slugOrId}/page/${list[0]?.id}`);
59 return;
60 }
61
62
63
64 let cancelled = false;
65 workspaceApi
66 .pages(wsId, { parent: null, limit: 5 })
67 .then(async (existing) => {
68 if (existing.length > 0) {
69 if (!cancelled) router.replace(`/w/${slugOrId}/page/${existing[0]?.id}`);
70 return;
71 }
72 const home = await createHome(wsId);
73 if (!cancelled && home) router.replace(`/w/${slugOrId}/page/${home.id}`);
74 })
75 .catch(() => {
76
77 });
78 return () => {
79 cancelled = true;
80 };
81
82 }, [workspace.data?.id, pages.data, slugOrId, router]);
83
84 return (
85 <div className="flex h-full items-center justify-center text-sm text-muted-foreground" role="status">
86 Opening your workspace…
87 </div>
88 );
89}
90
91async function createHome(workspaceId: string) {
92 const { pageApi } = await import("@/lib/api");
93 return pageApi.create({ workspaceId, parentId: null, title: "Home" });
94}
95